package com.example.testapp.activity.activity.study;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.testapp.R;
import com.example.testapp.activity.activity.SuperActivity;
import com.example.testapp.activity.http.AsyncHttpUtil;
import com.example.testapp.activity.model.NewsItem;
import com.example.testapp.activity.view.ErrorHintView;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import cz.msebera.android.httpclient.Header;

/**
 * Created by l on 2016/9/19.
 */
public class NewsDetailActivity extends SuperActivity {

    private WebView mWebview;
    private TextView title;
    private ErrorHintView mErrorHintView;

    private NewsItem item;
    private String PATH = "http://wcf.open.cnblogs.com/news/item/";

    public static int VIEW = 1;
    /**显示断网**/
    public static int VIEW_WIFIFAILUER = 2;
    /** 显示加载数据失败 **/
    public static int VIEW_LOADFAILURE = 3;
    public static int VIEW_LOADING = 4;

    private String url;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_detail);
        getWindow().setBackgroundDrawable(null);
        initView();
        initData();
    }

    @Override
    protected void obtainInfo() {

    }

    private void initData() {
        Intent intent = this.getIntent();
        item = (NewsItem) intent.getSerializableExtra("item");
        if(item != null){
            title.setText(item.getTitle());
            url = PATH + item.getId();
            showLoading(VIEW_LOADING);
            loadNewsDetailInfo(url);
        }
    }

    private void initView() {
        RelativeLayout headView = (RelativeLayout) this.findViewById(R.id.head);
        RelativeLayout leftBack = (RelativeLayout) this.findViewById(R.id.back_left);
        title = (TextView)headView.findViewById(R.id.head_title);
        mWebview = (WebView)this.findViewById(R.id.webview);
        mErrorHintView = (ErrorHintView)this.findViewById(R.id.hintView);
        LinearLayout top = (LinearLayout)this.findViewById(R.id.toolbar_top);
        LinearLayout comment = (LinearLayout)this.findViewById(R.id.toolbar_comment);
        LinearLayout save = (LinearLayout)this.findViewById(R.id.toolbar_save);

        leftBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        top.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mWebview.scrollTo(0, 0);
            }
        });

        comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, NewsCommentActivity.class);
                intent.putExtra("id", item.getId());
                intent.putExtra("title", item.getTitle());
                startActivity(intent);
            }
        });

        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("image/*");
                intent.putExtra(Intent.EXTRA_SUBJECT, "Share");
                intent.putExtra(Intent.EXTRA_TEXT, "Text");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(Intent.createChooser(intent, item.getTitle()));
            }
        });
    }

    /**
     * 显示动态加载界面
     *
     * @param i
     */
    private void showLoading(int i) {
        mErrorHintView.setVisibility(View.GONE);
        mWebview.setVisibility(View.GONE);

        switch (i){
            case 1:
                mErrorHintView.hideLoading();
                mWebview.setVisibility(View.VISIBLE);
                break;
            case 2:
                mErrorHintView.hideLoading();
                mErrorHintView.netError(new ErrorHintView.OperateListener() {
                    @Override
                    public void operate() {
                        showLoading(VIEW_LOADING);
                        loadNewsDetailInfo(url);
                    }
                });
                break;
            case 3:
                 mErrorHintView.hideLoading();
                 mErrorHintView.loadFailure(new ErrorHintView.OperateListener() {
                     @Override
                     public void operate() {
                         showLoading(VIEW_LOADING);
                         loadNewsDetailInfo(url);
                     }
                 });
                break;
            case 4:
                mErrorHintView.loadingdata();
                break;
        }
    }

    /**
     * 加载详情内容
     * @param url
     */
    private void loadNewsDetailInfo(String url) {
        AsyncHttpUtil.get(url, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                 if(responseBody != null && responseBody.length > 0){
                     showLoading(VIEW);
                     ByteArrayInputStream bis = new ByteArrayInputStream(responseBody);
                     String result = parseDetailContentXml(bis);
                     initWebView(result);
                 }else{
                     showLoading(VIEW_LOADFAILURE);
                 }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                  showLoading(VIEW_WIFIFAILUER);
            }
        });
    }

    private void initWebView(String result) {
        // 如果访问的页面中有Javascript，则webview必须设置支持Javascript
        mWebview.getSettings().setJavaScriptEnabled(true);
        mWebview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

        // 触摸焦点起作用
        mWebview.requestFocus();
        // 取消滚动条
        mWebview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        mWebview.setHorizontalScrollBarEnabled(false); //水平不显示
        mWebview.setVerticalScrollBarEnabled(false); //垂直不显示

        // 设置WevView要显示的网页
        mWebview.loadDataWithBaseURL(null, result, "text/html", "UTF-8", null);
        // 设置不可缩放
        mWebview.getSettings().setSupportZoom(false);
        mWebview.getSettings().setBuiltInZoomControls(false);

        mWebview.setWebViewClient(new MyWebViewClient());
        mWebview.setWebChromeClient(new WebChromeClient());
    }

    class MyWebViewClient extends WebViewClient{

        @SuppressLint("LongLogTag")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if(!TextUtils.isEmpty(url)){
                Log.d("shouldOverrideUrlLoading", "onPageFinished");
                mWebview.loadUrl(url);
            }
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            String title = view.getTitle();
            if(TextUtils.isEmpty(title)){
                return;
            }
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            Log.d("onReceivedError", "onReceivedError");
        }
    }

    private String parseDetailContentXml(InputStream is) {
        String result = null;
        XmlPullParser parser = Xml.newPullParser();
        try {
            parser.setInput(is, "UTF-8");
            int event = parser.getEventType();
            while (event != XmlPullParser.END_DOCUMENT){
                switch (event){
                    case XmlPullParser.START_DOCUMENT:
                        break;
                    case XmlPullParser.START_TAG:
                         if("Content".equals(parser.getName())){
                             result = parser.nextText();
                         }
                        break;
                    case XmlPullParser.TEXT:
                        break;
                    case XmlPullParser.END_TAG:
                        break;
                }
                event = parser.next();
            }
        }catch (XmlPullParserException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        return result;
    }
}
